package com.dht.xiao.jianye.utils;

import android.support.annotation.NonNull;

import com.dht.xiao.jianye.bean.newdata.LoginNewBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;


import cn.dlc.commonlibrary.utils.PrefUtil;

/**
 *
 */

public class UserHelper {

    private static UserHelper instance = new UserHelper();
    private final Gson mGson;
    private static final String USER_INFO = "user_info";

    /**
     * 缓存在内存中的用户信息
     */
    public static class UserInfo {
        private String token; // 登录token

        public void updateFrom(String data) {
            if (data != null) {
                token = data;
            }
        }



        public void reset() {
            token = null;
        }
    }

    private static UserInfo mUserInfo;

    private UserHelper() {
        mGson = new GsonBuilder().serializeNulls().create();
        loadUserInfoFromFile();
        if (mUserInfo == null) {
            mUserInfo = new UserInfo();
        }
    }

    public static UserHelper get() {
        return instance;
    }

    /**
     * 保存登录用户信息
     *
     */
    public void saveUserInfo(String data) {
        mUserInfo.updateFrom(data);
        saveUserInfoToFile();
    }



    /**
     * 保存用户信息到文件中
     */
    private void saveUserInfoToFile() {
        String json = mGson.toJson(mUserInfo);
        PrefUtil.getDefault().putString(USER_INFO, json).apply();
    }

    private void loadUserInfoFromFile() {
        String json = PrefUtil.getDefault().getString(USER_INFO, "");
        try {
            UserInfo userInfo = mGson.fromJson(json, UserInfo.class);
            if (userInfo != null) {
                mUserInfo = userInfo;
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出账号
     */
    public void logout() {
        // 发送退出登录消息
        mUserInfo.reset();
        saveUserInfoToFile();
    }

    private void checkEmptyAndLoad(Object value) {
        if (value == null) {
            loadUserInfoFromFile();
        }
    }



    /**
     * 返回非null的字符串
     *
     * @param ori
     * @return
     */
    private static @NonNull
    String returnNotNull(String ori) {
        return ori == null ? "" : ori;
    }



    public String getToken() {
        checkEmptyAndLoad(mUserInfo.token);
        return returnNotNull(mUserInfo.token);
    }



}
